import pyautogui as pag
import pyautogui

import win32gui
import win32con
import time
import win32clipboard as clipboard
import os,shutil
import os.path as osp
import numpy as np
import cv2

from tool import filesystem
# from tool import filesystem
# -i https://pypi.tuna.tsinghua.edu.cn/simple
# # clear clipboard first
os.system("echo off | clip")
clipboard.OpenClipboard()
clipboard.EmptyClipboard()
clipboard.CloseClipboard()


#获取剪切板内容
def get_clipboard_text():
    clipboard.OpenClipboard()
    t = clipboard.GetClipboardData()
    clipboard.CloseClipboard()
    return t

#写入剪切板内容
def set_clipboard_text(aString):
    clipboard.OpenClipboard()
    clipboard.EmptyClipboard()
    clipboard.SetClipboardData(win32con.CF_TEXT, aString)
    clipboard.CloseClipboard()

#清空剪切板内容
def clear_clipboard_text():
    clipboard.OpenClipboard()
    clipboard.EmptyClipboard()
    clipboard.CloseClipboard()


def win_screenshot(region):
    img = pyautogui.screenshot(region=region) # x,y,w,h  

    img = np.asarray(img)

    bgr_img = img[:, : , ::-1]
    # cv2.imwrite("1.jpg", bgr_img)
    return bgr_img

class AutoClick:
    def __init__(self):
        self.default_position = [0, 0]

        # self.水印开始位置   = [749, 143]  #   
        # self.水印结束位置   = [927, 143]  #
        # self.水印开始位置   = [141, 142]  #   
        # self.水印结束位置   = [261, 145]  #    
        self.水印开始位置   = [797, 564]  #  
        self.水印结束位置   = [936, 562]  #  
        self.水印开始位置2   = [930, 531]  #  
        self.水印结束位置2   = [863, 531]  #  
        self.水印开始位置3   = [873, 516]  #  
        self.水印结束位置3   = [873, 516]  #  

        self.擦除 = [900, 693]
        self.擦除_状态_check = [410, 325, 10, 10]
        self.图片位置 = [1128, 138]

        self.保存 = [743, 695]
        self.保存_地址栏 = [629, 50]
        self.保存_地址栏_转到 = [707, 49]
        self.保存_地址栏_保存 = [788, 504]
        self.保存_地址栏_取消 = [888, 505]
        self.保存_地址栏_截图 = [380, 7, 40, 23]

        self.删除当前图片 = [1203, 92]


        self.图片列表_check = [1070, 120, 10, 10]
        self.添加文件夹 = [645, 340]
        self.选择文件夹 = [780, 510]

        self.删除所有 = [1111, 702]
        self.删除所有_确认 = [324, 403]


    def reset_window(self):
        """
        将窗口移动至固定位置
        """
        is_ok = False
        hWndList = []  
        win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)  
        for hwnd in hWndList:
            clsname = win32gui.GetClassName(hwnd)
            title = win32gui.GetWindowText(hwnd)
            
            # Photo Eraser  Qt5QWindowIcon
            if title == "Photo Eraser" and clsname == "Qt5QWindowIcon":
                posi = win32gui.GetWindowRect(hwnd)
                w, h = posi[2] - posi[0],  posi[3] - posi[1]
                win32gui.MoveWindow(hwnd, self.default_position[0],self.default_position[1],w, h, 0)
                is_ok = True
                # print("w: ", w, "  h: ", h)
        return is_ok

    def check_msg(self):
        pag.doubleClick(    x=self.default_position[0] + self.聊天[0], 
                            y=self.default_position[1] + self.聊天[1], 
                            interval=0.1)
        time.sleep(0.2)
        pag.click(  x=self.default_position[0] + self.first_msg_position[0], 
                    y=self.default_position[1] + self.first_msg_position[1], 
                    interval=0.1)

    def deal_one_img(self, save_path):
        pag.click(  x=self.图片位置[0], 
                    y=self.图片位置[1],
                    interval=0.1)
        time.sleep(0.5)
        
        pag.mouseDown(self.水印开始位置[0], self.水印开始位置[1])
        pag.move(self.水印结束位置[0]-self.水印开始位置[0], self.水印结束位置[1]-self.水印开始位置[1])
        pag.mouseUp()
        time.sleep(0.2)
        pag.mouseDown(self.水印开始位置2[0], self.水印开始位置2[1])
        pag.move(self.水印结束位置2[0]-self.水印开始位置2[0], self.水印结束位置2[1]-self.水印开始位置2[1])
        pag.mouseUp()
        pag.mouseDown(self.水印开始位置3[0], self.水印开始位置3[1])
        pag.move(self.水印开始位置3[0]-self.水印开始位置3[0], self.水印开始位置3[1]-self.水印开始位置3[1])
        pag.mouseUp()

        pag.click(  x=self.擦除[0], 
                    y=self.擦除[1],
                    interval=0.1)

        cnt = 20
        while cnt > 0:
            time.sleep(0.5)
            img = win_screenshot(self.擦除_状态_check)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)
            print(mean)
            # 判断擦除完完成
            cnt -=1
            if 164.98 < mean < 165.02:
                continue
            break

        time.sleep(0.5)
        pag.click(  x=self.保存[0], 
                    y=self.保存[1],
                    interval=0.1)
                    
        while True:
            img = win_screenshot(self.保存_地址栏_截图)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)

            # 判断弹框完成
            if mean > 220:
                break
            time.sleep(0.5)

        pag.click(  x=self.保存_地址栏[0], 
                    y=self.保存_地址栏[1],
                    interval=0.1)
        time.sleep(0.3)

        pag.typewrite(save_path)
        # pag.KEYBOARD_KEYS
        pag.typewrite(["enter"], interval=0.1)
        time.sleep(0.3)
        pag.click(  x=self.保存_地址栏_转到[0], 
                    y=self.保存_地址栏_转到[1],
                    interval=0.1)
        time.sleep(0.3)
        
        pag.click(  x=self.保存_地址栏_保存[0], 
                    y=self.保存_地址栏_保存[1],
                    interval=0.1)
        time.sleep(0.3)

        # 检查多余的保存框
        while True:
            img = win_screenshot(self.保存_地址栏_截图)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)

            # 判断弹框完成
            if mean > 220:
                pag.click(  x=self.保存_地址栏_取消[0], 
                            y=self.保存_地址栏_取消[1],
                            interval=0.1)
                time.sleep(0.3)
            else:
                break
            time.sleep(1)

        pag.click(  x=self.删除当前图片[0], 
                    y=self.删除当前图片[1],
                    interval=0.1)
        time.sleep(0.5)

    def auto_run(self, data_dir):
        """
        自动擦除并保存
        """
        ori_files = filesystem.get_all_filepath(data_dir, [".jpg"])
        save_path = data_dir + "_deal"
        if osp.exists(save_path):
            files = filesystem.get_all_filepath(save_path, [".jpg"])
            if len(ori_files) == len(files):
                print("ok. ", data_dir)
                return
            else:
                shutil.rmtree(save_path)
        os.makedirs(save_path, exist_ok=True)

        # 移除所有图片
        pag.click(  x=self.删除所有[0], 
                    y=self.删除所有[1],
                    interval=0.1)
        time.sleep(1)
        pag.click(  x=self.删除所有_确认[0], 
                    y=self.删除所有_确认[1],
                    interval=0.1)
        time.sleep(1)

        # 添加图片
        pag.click(  x=self.添加文件夹[0], 
                    y=self.添加文件夹[1],
                    interval=0.1)
        time.sleep(1)

        while True:
            img = win_screenshot(self.保存_地址栏_截图)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)

            # 判断弹框完成
            if mean > 220:
                break
            time.sleep(0.5)

        pag.click(  x=self.保存_地址栏[0], 
                    y=self.保存_地址栏[1],
                    interval=0.1)
        time.sleep(0.3)
        pag.typewrite(data_dir)
        # pag.KEYBOARD_KEYS
        pag.typewrite(["enter"], interval=0.1)
        time.sleep(0.5)
        pag.click(  x=self.保存_地址栏_转到[0], 
                    y=self.保存_地址栏_转到[1],
                    interval=0.1)
        time.sleep(0.3)
        pag.click(  x=self.选择文件夹[0], 
                    y=self.选择文件夹[1],
                    interval=0.1)
        time.sleep(1)
        
        # 判断图片加载完成
        cnt = 120
        while cnt > 0:
            time.sleep(1)
            cnt -=1
            img = win_screenshot(self.图片列表_check)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)
            print("mean: ", mean)
            # 判断操作完成
            if 67.99 < mean < 68.01:
                continue
            break

        while True:
            self.deal_one_img(save_path)
            time.sleep(0.5)
            img = win_screenshot(self.图片列表_check)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            mean = np.mean(gray)
            print("mean: ", mean)
            # 判断操作完成
            if 67.99 < mean < 68.01:
                break




def main(data_dir):
    # for i in range(10):
    #     pag.moveTo(300, 300, duration=0.25)
    #     pag.moveTo(400, 300, duration=0.25)
    #     pag.moveTo(400, 400, duration=0.25)
    #     pag.moveTo(300, 400, duration=0.25)
    manager = AutoClick()



    if not manager.reset_window():
        print("reset_window ERROR...")
        exit()
    

    dirs = filesystem.get_last_dir(data_dir)
    for dir in dirs:
        if dir.endswith("deal"): continue
        print(dir)
        manager.auto_run(dir)

def reset_window_pos(targetTitle):  
    hWndList = []  
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)  
    for hwnd in hWndList:
        clsname = win32gui.GetClassName(hwnd)
        title = win32gui.GetWindowText(hwnd)
        if clsname == "WeChatMainWndForPC":
            print(clsname, "       ", title)
            posi = win32gui.GetWindowRect(hwnd)
            w, h = posi[2] - posi[0],  posi[3] - posi[1]
            win32gui.MoveWindow(hwnd, 300,300,w, h, 0)
            
            print("w: ", w, "  h: ", h)
        # if (title.find(targetTitle) >= 0):    #调整目标窗口到坐标(600,300),大小设置为(600,600)
            # win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 300,300,0,0, win32con.SWP_SHOWWINDOW)
            


if __name__ == "__main__":
        # data_dir = r"E:\work\dataset\video\boat\mda-nfppn2rqug2yb7th\0"

    data_dir = r"F:\demo\Floating_objects\WeChat_20230603154612\0"
    # for i in range(10):
    main(data_dir)


    # ori_dir = r"F:\demo\Floating_objects\WeChat_20230603154612\0"
    # deal_dir = r"F:\demo\Floating_objects\WeChat_20230603154612\0_deal"
    # for p in filesystem.get_all_filepath(deal_dir, [".jpg"]):
    #     filename = osp.basename(p)
    #     ori_path = osp.join(ori_dir, filename.replace("_Copy", ""))
    #     if osp.exists(ori_path):
    #         os.remove(ori_path)
